const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');
const { requireAuth } = require('../middleware/auth');

// 获取用户素材列表
router.get('/', requireAuth, async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      type_id, 
      search 
    } = req.query;
    const userId = req.user.id;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    let whereClause = 'WHERE um.user_id = ?';
    const params = [userId];
    
    if (type_id) {
      whereClause += ' AND um.type_id = ?';
      params.push(type_id);
    }
    
    if (search) {
      whereClause += ' AND um.name LIKE ?';
      params.push(`%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.execute(
      `SELECT COUNT(*) as total FROM user_materials um ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        um.id,
        um.name,
        um.type_id,
        um.url,
        um.thumbnail,
        um.width,
        um.height,
        um.file_size,
        um.file_type,
        um.tags,
        um.created_at,
        um.updated_at,
        mt.name as type_name
      FROM user_materials um
      LEFT JOIN material_types mt ON um.type_id = mt.id
      ${whereClause}
      ORDER BY um.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.execute(query, [...params, limit, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        url: row.url,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        file_size: row.file_size,
        file_type: row.file_type,
        tags: row.tags ? JSON.parse(row.tags) : [],
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        material_type: row.type_name ? {
          data: {
            id: row.type_id,
            attributes: {
              name: row.type_name
            }
          }
        } : null
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          pageCount: Math.ceil(total / parseInt(pageSize)),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取用户素材列表失败:', error);
    res.status(500).json({ error: { message: '获取用户素材列表失败' } });
  }
});

// 创建用户素材
router.post('/', requireAuth, async (req, res) => {
  try {
    const { data } = req.body;
    const userId = req.user.id;
    
    const {
      name,
      type_id,
      url,
      thumbnail,
      width,
      height,
      file_size,
      file_type,
      tags
    } = data;
    
    if (!name || !url) {
      return res.status(400).json({ error: '素材名称和URL不能为空' });
    }
    
    const [result] = await db.execute(
      `INSERT INTO user_materials 
       (user_id, name, type_id, url, thumbnail, width, height, file_size, file_type, tags) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        userId,
        name,
        type_id || null,
        url,
        thumbnail || null,
        width || null,
        height || null,
        file_size || null,
        file_type || null,
        tags ? JSON.stringify(tags) : null
      ]
    );
    
    const [rows] = await db.execute(
      `SELECT 
         um.*,
         mt.name as type_name
       FROM user_materials um
       LEFT JOIN material_types mt ON um.type_id = mt.id
       WHERE um.id = ?`,
      [result.insertId]
    );
    
    const row = rows[0];
    const responseData = {
      id: row.id,
      attributes: {
        name: row.name,
        url: row.url,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        file_size: row.file_size,
        file_type: row.file_type,
        tags: row.tags ? JSON.parse(row.tags) : [],
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        material_type: row.type_name ? {
          data: {
            id: row.type_id,
            attributes: {
              name: row.type_name
            }
          }
        } : null
      }
    };
    
    res.status(201).json({ data: responseData });
  } catch (error) {
    console.error('创建用户素材失败:', error);
    res.status(500).json({ error: '创建用户素材失败' });
  }
});

// 删除用户素材
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    // 检查素材是否存在且属于当前用户
    const [rows] = await db.execute(
      'SELECT * FROM user_materials WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '素材不存在或无权限删除' });
    }
    
    await db.execute(
      'DELETE FROM user_materials WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除用户素材失败:', error);
    res.status(500).json({ error: '删除用户素材失败' });
  }
});

// 获取单个用户素材详情
router.get('/:id', requireAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    const [rows] = await db.execute(
      `SELECT 
         um.*,
         mt.name as type_name
       FROM user_materials um
       LEFT JOIN material_types mt ON um.type_id = mt.id
       WHERE um.id = ? AND um.user_id = ?`,
      [id, userId]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '素材不存在' });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        name: row.name,
        url: row.url,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        file_size: row.file_size,
        file_type: row.file_type,
        tags: row.tags ? JSON.parse(row.tags) : [],
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        material_type: row.type_name ? {
          data: {
            id: row.type_id,
            attributes: {
              name: row.type_name
            }
          }
        } : null
      }
    };
    
    res.json({ data });
  } catch (error) {
    console.error('获取用户素材详情失败:', error);
    res.status(500).json({ error: '获取用户素材详情失败' });
  }
});

module.exports = router;